from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from  tools.myredis import r
import json
import random

class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
    userlist = []
    kflist=[]
    kf = {}
    room = {}
    #    room_name = 'chat_all_data'
    def websocket_connect(self, message):
        print("有人进行连接了。。。。")

        roomnum = self.scope['url_route']['kwargs']['group']
        if 'kf'in roomnum:
            if roomnum not in self.kflist:
                self.kflist.append(roomnum)
                self.kflist[roomnum]=self.channel_name
            # r.list_push('kflist',roomnum)
            async_to_sync(self.channel_layer.group_add)(str(roomnum), self.channel_name)
            self.accept()
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)(
                roomnum,  # 房间组名
                {
                    'type': 'send_to_chrome',  # 消费者中处理的函数
                    'data':{ 'data':'欢迎回来',
                                'action':'系统消息'
                                 }
                }
            )
        else:#用户链接
            self.userlist.append(roomnum)
            # r.list_push('userlist',roomnum)
            async_to_sync(self.channel_layer.group_add)(str(roomnum), self.channel_name)
            # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
            self.accept()
            # channel_layer = get_channel_layer()
            # async_to_sync(channel_layer.group_send)(
            #     roomnum,  # 房间组名
            #     {
            #         'type': 'send_to_chrome',  # 消费者中处理的函数
            #         'data': { 'data':'客服正在接入，请耐心等待',
            #                      'action':'系统消息'
            #                      }
            #     }
            # )
            if len(self.kflist) > 0:
                kf = random.choice(self.kflist)
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    kf,  # 房间组名
                    {
                        'type': 'send_to_chrome',  # 消费者中处理的函数
                        'data':{ 'data':roomnum,
                                 'action':'用户请求接入'
                                 }
                    }
                )

    def websocket_receive(self, message):
        # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
        # 消息持久化 mysql  redis
        print(message['text'])

        data = json.loads(message['text'])
        message = data['text']
        necter=data['type']
        roomnum = self.scope['url_route']['kwargs']['group']
        print(roomnum)
        if 'kf' in roomnum:
            async_to_sync(self.channel_layer.group_add)(str(message), self.channel_name) #加入用户房间
            self.kflist.remove(roomnum)
            self.room[roomnum] = message # 记录客服和用户的关系
            self.accept()
            # r.list_del('kflist',roomnum)
            # r.list_push('wkf',roomnum)
        else:
            channel_layer = get_channel_layer()

            async_to_sync(channel_layer.group_send)(
                roomnum,#房间组名
                {
                    'type':'send_to_chrome', #消费者中处理的函数
                    'data':{ 'data':message,
                                 'action':necter
                                 }
                }
            )

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        roomnum = self.scope['url_route']['kwargs']['group']
        if roomnum.find('kf')>0:#客服断开链接
           self.kflist.remove(roomnum)
        else:
            self.send(json.dumps('用户已下线', ensure_ascii=False))
            # kf=self.room.get(roomnum)
            # self.send(text_data=str(kf))
            # async_to_sync(self.channel_layer.group_add)(str(kf), self.kf[str(kf)])
            # 将客户端从对应的组中移除
            async_to_sync(self.channel_layer.group_discard)(
                roomnum,
                self.channel_name
            )
            # 断开链接
            raise StopConsumer()

    # 自定义的处理房间组内的数据
    def send_to_chrome(self, event):
        try:
            data = event.get('data')
            # 接收房间组广播数据，将数据发送给websocket
            self.send(json.dumps(data, ensure_ascii=False))
        except Exception as e:
            pass

